﻿using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel.Design;
using System.IO;
using System.Text.Json;

namespace WebsocketDemo.CollaborativeEditing
{
    /// <summary>
    /// 协同编辑word版,如需要加入业务,需要添加group概念,好区分到底是哪个文档
    /// </summary>
    public class CollaborativeEditing:Hub
    {

        private IMemoryCache _memoryCache;
        public CollaborativeEditing(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }
        /// <summary>
        /// 发送消息-所有人
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendAllMessage(string message)
        {
          
              await Clients.All.SendAsync("SendAllMessage", $"{message}");
        }
        /// <summary>
        /// 发送消息-所有人
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendOtherMessage(string message)
        {

            //await Clients.OthersInGroup("").SendAsync("SendOtherMessage", $"{message}");
            await Clients.Others.SendAsync("SendOtherMessage", $"{message}");
        }

        /// <summary>
        /// 发送消息-所有人
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public void LogData(string message)
        {
            try 
            {
                List<dynamic> cachedata = _memoryCache.Get<List<dynamic>>("200");

                JObject data = JsonConvert.DeserializeObject<JObject>(message);
                string method = data.SelectToken("method").Value<string>();
                int starindex = data.SelectToken("input.0").Value<int>();
                int endindex = data.SelectToken("input.1").Value<int>();
                string tokenstr = "";
                JsonElement inputdata=new JsonElement();
                if (data.SelectToken("input.2") != null)
                {
                    var datatoken = data.SelectToken("input.2").Value<dynamic>() ;
                    tokenstr = JsonConvert.SerializeObject(datatoken);
                    inputdata= System.Text.Json.JsonSerializer.Deserialize<dynamic>(tokenstr);
                }
                
                if (method == "splice")
                {
                    Splice(cachedata, starindex, endindex, !string.IsNullOrEmpty(tokenstr), inputdata);
                }
                if (method == "slice")
                {
                    Splice(cachedata, starindex, endindex-starindex, !string.IsNullOrEmpty(tokenstr), inputdata);
                }
            }
            catch(Exception e) 
            {
            }
        }

        /// <summary>
        /// js的split
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="start"></param>
        /// <param name="deleteCount"></param>
        /// <param name="items"></param>
        private void Splice<T>(List<T> list, int start, int deleteCount,bool hanveAdd, params T[] items)
        {
            // 删除元素
            if (deleteCount > 0)
            {
                list.RemoveRange(start, deleteCount);
            }

            // 插入元素
            if (hanveAdd)
            {
                list.InsertRange(start, items);
            }
        }

        /// <summary>
        /// 接受加载消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task GetLoadData(string message)
        {
            //var a = Context.UserIdentifier;
            //var b = Context.User;
            //映射人员ID和链接的,demo不用管
            if (Context.Items.TryGetValue(Context.ConnectionId, out object? val))
            {
                Context.Items["Context.ConnectionId"] = message;
            }
            else
            {
                Context.Items.TryAdd(Context.ConnectionId, message);
            }
            //await Clients.Caller.SendAsync("ReceiveLoad", $"成功");
        }
        /// <summary>
        /// 接受消息并回发消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToServer(string message)
        {
         
            LogData(message);

            await SendOtherMessage(message);

            // 示例：将接收到的消息回发给发送者，模拟服务器响应
            await Clients.Caller.SendAsync("ReceiveServerResponse", $"成功");
        }

        public async Task addToGroup(string message)
        {

            await Groups.AddToGroupAsync(Context.ConnectionId, message);
        }




        public override Task OnDisconnectedAsync(Exception exception)
        {
            if (Context.Items.TryGetValue(Context.ConnectionId, out object datavalue))
            {
                Context.Items.Remove(Context.ConnectionId);
            }
            // 当客户端断开连接时，从组中移除或进行其他清理
            return base.OnDisconnectedAsync(exception);
        }

        
    }
}
